package com.cutthroatcreations.woodenrailway;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.TimeZone;

import com.cutthroatcreations.woodenrailway.Train.Year;
import com.cutthroatcreations.woodenrailway.json.JSONArray;
import com.cutthroatcreations.woodenrailway.json.JSONObject;
import com.google.gson.Gson;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends Activity {

	private ImageView allItems;
	private ImageView colMan;
	private String trainsJson;
	private String trains;
	private ProgressDialog progressDialog;
	private Context ctx;
	private User user;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		ctx = this;
		trainsJson = getIntent().getStringExtra("trains");
		allItems = (ImageView) findViewById(R.id.allItems);
		colMan = (ImageView) findViewById(R.id.colManger);
		if (WoodenApplication.allTrains == null) {
			AsyncTask<String, Void, TrainYear> loadTask = new loadList();
			loadTask.execute(trainsJson);
		}

		allItems.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {

				Intent intent = new Intent(getApplication(),
						YearListActivity.class);

				intent.putExtra("trains", trains);

				startActivity(intent);

			}
		});

		colMan.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {

				Intent intent = new Intent(getApplication(),
						CollectionManagerActivity.class);

				startActivity(intent);

			}
		});
	}

	private class loadList extends AsyncTask<String, Void, TrainYear> {

		@Override
		protected void onPreExecute() {
			progressDialog = ProgressDialog.show(ctx, "LOADING TRAINS",
					"Please Wait....", true);
		};

		@Override
		protected TrainYear doInBackground(String... params) {
			TrainYear ty = new TrainYear();
			ty.trains = populateTrains(params[0]);
			ty.makeYears(ty.trains);
			return ty;

		}

		// Populate trains table with remote DB info
		private ArrayList<Train> populateTrains(String res) {
			ArrayList<Train> list = new ArrayList<Train>();
			try {
				String trainJson = res.replace("|||", "&");
				trainJson = trainJson.replace("|", " ");
				JSONArray jArray = new JSONArray(trainJson);

				for (int i = 0; i < jArray.length(); i++) {

					JSONObject json_data = jArray.getJSONObject(i);
					Gson gson = new Gson();

					Train train = gson.fromJson(json_data.get("Train")
							.toString(), Train.class);

					list.add(train);
					// addNewDBTrain(train);

				}
				return list;
			} catch (Exception e) {
				e.printStackTrace();
				Toast.makeText(ctx, "Invalid Format", Toast.LENGTH_SHORT)
				.show();
				return null;
			}
			
		}

		@Override
		protected void onPostExecute(TrainYear result) {

			super.onPostExecute(result);
			if(result == null){
				finish();
			}
			if (WoodenApplication.getAllTrains() == null) {

				try {
					setAllTrains(result.trains);
					//setUser();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

			progressDialog.dismiss();
		}

		private boolean setAllTrains(ArrayList<Train> t) throws Exception {
			Field field = WoodenApplication.class.getDeclaredField("allTrains");
			field.setAccessible(true);
			field.set(null, t);
			return true;
		}
		
		private boolean setUser() throws Exception {
			Field field = WoodenApplication.class.getDeclaredField("user");
			field.setAccessible(true);
			field.set(null, new User(WoodenApplication.allTrains.get(0).getUser_id(), getIntent().getStringExtra("email"), getIntent().getStringExtra("password")));
			return true;
		}

	}

	private class TrainYear {
		public ArrayList<Train> trains;
		ArrayList<Integer> yearSetAll;

		public void makeYears(ArrayList<Train> trains) {
			for (Train train : trains) {

				yearSetAll = new ArrayList<Integer>();
				for (Year year : train.years) {
					String end = year.end_year;
					if (end.equalsIgnoreCase("present")) {
						end = String.valueOf(Calendar.getInstance(
								TimeZone.getDefault()).get(Calendar.YEAR));
					}
					int num = 0;
					for (int i = Integer.parseInt(year.start_year); i < Integer
							.parseInt(end) + 1; i++) {
						num++;
						if (i == Integer.parseInt(end))
							train.setNumYears(num);
						yearSetAll.add(i);
					}
				}
				train.addAllYears(yearSetAll);
			}
		}
	}

}
